package com.ffggffgfv.backend.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.ffggffgfv.backend.config.AlipayConfig;
import com.ffggffgfv.backend.dto.AlipayRequestDTO;
import com.ffggffgfv.backend.dto.AlipayResponseDTO;
import com.ffggffgfv.backend.entity.Order;
import com.ffggffgfv.backend.service.OrderService;
import com.ffggffgfv.backend.util.JWTUtil;
import com.ffggffgfv.backend.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 支付宝沙箱支付控制器
 */
@RestController
@RequestMapping("/api/alipay")
public class AlipayController {

    @Autowired
    private AlipayClient alipayClient;

    @Autowired
    private AlipayConfig alipayConfig;

    @Autowired
    private OrderService orderService;

    @Autowired
    private JWTUtil jwtUtil;

    /**
     * 支付宝支付接口
     *
     * @param alipayRequestDTO 支付请求参数
     * @param token JWT令牌
     * @return 支付响应结果
     */
    @PostMapping("/pay")
    public Result alipayPay(@RequestBody AlipayRequestDTO alipayRequestDTO, 
                           @RequestHeader(value = "Authorization") String token) {
        // 从令牌中获取用户ID
        Long userId = getUserIdFromToken(token);
        if (userId == null) {
            return Result.unauthorized("未登录或登录已过期");
        }

        // 参数验证
        if (alipayRequestDTO.getOrderNo() == null || alipayRequestDTO.getOrderNo().trim().isEmpty()) {
            return Result.validateFailed("订单号不能为空");
        }
        if (alipayRequestDTO.getTotalAmount() == null || alipayRequestDTO.getTotalAmount().trim().isEmpty()) {
            return Result.validateFailed("订单金额不能为空");
        }
        if (alipayRequestDTO.getSubject() == null || alipayRequestDTO.getSubject().trim().isEmpty()) {
            return Result.validateFailed("订单标题不能为空");
        }

        // 验证订单是否存在且属于当前用户
        Order order = orderService.getOrderByOrderNo(alipayRequestDTO.getOrderNo());
        if (order == null || !order.getUserId().equals(userId)) {
            return Result.validateFailed("订单不存在或无权访问");
        }

        // 检查订单状态，只有待支付的订单可以支付
        if (order.getStatus() != 0) {
            return Result.validateFailed("订单状态不正确，无法支付");
        }

        AlipayResponseDTO response = new AlipayResponseDTO();
        try {
            // 调用支付宝接口
            AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
            request.setNotifyUrl(alipayConfig.getNotifyUrl());
            request.setReturnUrl(alipayConfig.getReturnUrl());
            
            String bizContent = String.format(
                "{\"out_trade_no\":\"%s\"," +
                "\"total_amount\":\"%s\"," +
                "\"subject\":\"%s\"," +
                "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"," +
                "\"body\":\"%s\"}",
                alipayRequestDTO.getOrderNo(),
                alipayRequestDTO.getTotalAmount(),
                alipayRequestDTO.getSubject(),
                alipayRequestDTO.getBody() != null ? alipayRequestDTO.getBody() : ""
            );
            
            request.setBizContent(bizContent);
            String form = alipayClient.pageExecute(request).getBody();
            
            response.setCode("200");
            response.setMessage("支付链接生成成功");
            response.setPayUrl(form);
            
            return Result.success(response, "支付链接生成成功");
        } catch (AlipayApiException e) {
            response.setCode("500");
            response.setMessage("支付失败：" + e.getMessage());
            return Result.failed("支付失败：" + e.getMessage());
        }
    }

    /**
     * 支付宝异步通知接口
     *
     * @param trade_status   交易状态
     * @param out_trade_no   商户订单号
     * @param trade_no       支付宝交易号
     * @return 处理结果
     */
    @PostMapping("/notify")
    public String notify(@RequestParam String trade_status,
                        @RequestParam String out_trade_no,
                        @RequestParam String trade_no) {
        try {
            // 处理支付宝异步通知
            if ("TRADE_SUCCESS".equals(trade_status)) {
                // 更新订单状态为支付成功
                orderService.updateOrderStatusByOrderNo(out_trade_no, 1, trade_no);
                return "success";
            } else if ("TRADE_CLOSED".equals(trade_status)) {
                // 更新订单状态为支付失败
                orderService.updateOrderStatusByOrderNo(out_trade_no, 4, trade_no);
                return "success";
            }
            return "fail";
        } catch (Exception e) {
            // 记录异常日志
            System.err.println("支付宝异步通知处理异常：" + e.getMessage());
            return "fail";
        }
    }

    /**
     * 支付宝同步回调接口
     *
     * @param out_trade_no 商户订单号
     * @param trade_no     支付宝交易号
     * @return 回调结果页面
     */
    @GetMapping("/return")
    public String returnUrl(@RequestParam String out_trade_no,
                          @RequestParam String trade_no) {
        try {
            // 查询订单状态
            Order order = orderService.getOrderByOrderNo(out_trade_no);
            if (order != null && order.getStatus() == 1) {
                return "支付成功，订单号：" + out_trade_no + "，支付宝交易号：" + trade_no;
            }
            return "支付处理中，请稍后查看订单状态";
        } catch (Exception e) {
            return "支付状态查询失败，请联系客服";
        }
    }

    /**
     * 从令牌中提取用户ID
     *
     * @param token JWT令牌
     * @return 用户ID
     */
    private Long getUserIdFromToken(String token) {
        try {
            if (token != null && token.startsWith("Bearer ")) {
                String jwtToken = token.substring(7);
                return jwtUtil.getUserIdFromToken(jwtToken);
            }
        } catch (Exception e) {
            // 令牌解析失败
        }
        return null;
    }
}
